package com.lijiajian.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lijiajian.base.BaseQuery;
import com.lijiajian.base.BaseService;
import com.lijiajian.dao.RoleMapper;
import com.lijiajian.dao.UserMapper;
import com.lijiajian.dao.UserRoleMapper;
import com.lijiajian.model.UserModel;
import com.lijiajian.pojo.SaleChance;
import com.lijiajian.pojo.User;
import com.lijiajian.pojo.UserRole;
import com.lijiajian.utils.AssertUtil;
import com.lijiajian.utils.Md5Util;
import com.lijiajian.utils.UserIDBase64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserService extends BaseService<User,Integer> {
    @Resource
    private UserMapper userMapper;
    @Resource
    UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;

    /**
     * 登录、校验
     * @param userName
     * @param userPwd
     * @return
     */
    public UserModel userLogin(String userName, String userPwd){
        //1、参数判断，判断用户姓名、用户密码非空
        checkLoginParams(userName,userPwd);
        //2、通过用户名查询用户对象，返回用户对象
        User user = userMapper.queryUserByName(userName);
        //3、判断用户对象是否为空
        AssertUtil.isTrue(user==null,"用户姓名不存在");
        //4、判断密码是否正确，比较客户端传递的用户密码与数据库中的用户密码
        checkUserPwd(userPwd,user.getUserPwd());
        //5、登录成功返回一个UserModel
        return buildUserModel(user);
    }

    /**
     * 修改密码
     * @param userId
     * @param oldPwd
     * @param newPwd
     * @param repeatPwd
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePassword(Integer userId,String oldPwd,String newPwd,String repeatPwd){
        //通过用户id查询用户记录，返回用户对象
        User user = userMapper.selectByPrimaryKey(userId);
        //判断用户是否存在
        AssertUtil.isTrue(null==user,"用户记录不存在");
        //参数校验
        checkPasswordParams(user,oldPwd,newPwd,repeatPwd);
        //设置用户的新密码
        user.setUserPwd(Md5Util.encode(newPwd));
        //执行更新，判断受影响的行数
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user)<1,"修改失败");

    }
    public List<User> getAllSales(){
        return userMapper.getAllSales();
    }

    /**
     * 添加用户
     * @param user
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addUser(User user){
        //参数校验
        checkUserParams(user.getUserName(),user.getEmail(),user.getPhone(),user.getId());
        //设置默认值
        user.setUserPwd(Md5Util.encode("123456"));
        user.setUpdateDate(new Date());
        user.setCreateDate(new Date());
        user.setIsValid(1);
        //执行添加操作
        AssertUtil.isTrue(userMapper.insertSelective(user)<1,"添加用户失败");
        //用户角色关联

        relationUserRole(user.getId(),user.getRoleIds());
    }

    /**
     * 用户角色关联
     * @param userId
     * @param roleIds
     */
    private void relationUserRole(Integer userId, String roleIds) {
        //通过用户id查询角色记录
       Integer count= userRoleMapper.countUserRoleByUserId(userId);
       if(count>0){
           //如果角色记录存在，则删除该用户对应的角色记录
           AssertUtil.isTrue(userRoleMapper.deleteUserRoleByUserId(userId)!=count,"用户角色关联失败");
       }
       //判断角色id是否存在，如果存在，则添加该用户对应的角色记录
        if(StringUtils.isNotBlank(roleIds)){
            String[] roleIdsArr = roleIds.split(",");
            List<UserRole> userRoleList = new ArrayList<>();
            for(String roleId:roleIdsArr){
                UserRole userRole = new UserRole();
                userRole.setRoleId(Integer.parseInt(roleId));
                userRole.setCreateDate(new Date());
                userRole.setUpdateDate(new Date());
                userRole.setUserId(userId);
                userRoleList.add(userRole);

            }
            //批量添加用户角色
            AssertUtil.isTrue(userRoleMapper.insertBatch(userRoleList)!=userRoleList.size(),"用户角色关联失败");

        }



    }

    /**
     * 修改用户
     * @param user
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateUser(User user){
        //判断id不能为空,并且存在一条记录
        AssertUtil.isTrue(null==user.getId(),"id不能为空");
        AssertUtil.isTrue(null==userMapper.selectByPrimaryKey(user.getId()),"待更新记录不存在");
        //参数校验
        checkUserParams(user.getUserName(),user.getEmail(),user.getPhone(),user.getId());
        //设置默认值
        user.setUpdateDate(new Date());
        //执行添加操作
        AssertUtil.isTrue(userMapper.updateByPrimaryKeySelective(user)!=1,"修改用户失败");

        //用户角色关联

        relationUserRole(user.getId(),user.getRoleIds());
    }

    /**
     * 删除用户
     * @param
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteUser(Integer[] ids){
        //判断id不能为空
       AssertUtil.isTrue(null==ids||ids.length==0,"待删除记录不存在");
       //执行删除操作
        AssertUtil.isTrue(userMapper.deleteBatch(ids)!=ids.length,"删除失败");

        //删除用户时要把关联的用户角色也删除掉
        for(Integer id:ids){
            Integer count = userRoleMapper.countUserRoleByUserId(id);
            if(count>0){
                AssertUtil.isTrue(userRoleMapper.deleteUserRoleByUserId(id)!=count,"删除用户角色失败");
            }
        }
    }

    /**
     * 重写方法为roleNames赋值以便前端页面显示
     * @param baseQuery
     * @return
     */
    @Override
    public Map<String, Object> queryByParamsForTable(BaseQuery baseQuery) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        PageHelper.startPage(baseQuery.getPage(),baseQuery.getLimit());
        List<User> users = selectByParams(baseQuery);
        //给每个user赋值roleNames
        for(User user:users){
            //得到roleNames
            String[] roleNames = roleMapper.selectRoleNames(user.getId());

            user.setRoleNames(roleNames);

        }
        PageInfo<User> pageInfo = new PageInfo<>(users);
        result.put("count",pageInfo.getTotal());
        result.put("data",pageInfo.getList());
        result.put("code", 0);
        result.put("msg", "");
        return result;
    }

    private void checkUserParams(String userName, String email, String phone, Integer id) {
        AssertUtil.isTrue(null==userName,"用户名不能为空");
        //如果是添加操作，数据库中无数据，只要通过名称查询到数据，表示用户名已存在
        //如果是更新操作，数据库有相应的数据，通过名称查询数据，可能是当前记录本身，也可能是别的记录，通过id来判断是不是当前记录本身
        User temp = userMapper.queryUserByName(userName);
        AssertUtil.isTrue(temp!=null&&!temp.getId().equals(id),"用户名已存在，请重新输入");
        AssertUtil.isTrue(null==email,"邮箱不能为空");
        AssertUtil.isTrue(null==phone,"手机号码不能为空");
    }

    private void checkPasswordParams(User user, String oldPwd, String newPwd, String repeatPwd) {
        //原始密码是否为空
        AssertUtil.isTrue(StringUtils.isBlank(oldPwd),"原始密码不能为空");
        //新密码是否为空
        AssertUtil.isTrue(StringUtils.isBlank(newPwd),"新密码不能为空");
        //确认密码是否为空
        AssertUtil.isTrue(StringUtils.isBlank(repeatPwd),"确认密码不能为空");

        //原始密码是否正确
        AssertUtil.isTrue(!user.getUserPwd().equals(Md5Util.encode(oldPwd)),"原始密码不正确");

        //新密码是否与原始密码一致
        AssertUtil.isTrue(newPwd.equals(oldPwd),"原始密码与新密码相同");

        //确认密码是否与新密码一致
        AssertUtil.isTrue(!repeatPwd.equals(newPwd),"确认密码与新密码不相同");
    }

    private UserModel buildUserModel(User user) {
        UserModel userModel=new UserModel();
        userModel.setRealName(user.getTrueName());
//        userModel.setUserId(user.getId());
        userModel.setUserIdStr(UserIDBase64.encoderUserID(user.getId()));
        userModel.setUserName(user.getUserName());
        return userModel;
    }

    private void checkUserPwd(String userPwd, String userPwd1) {
       userPwd= Md5Util.encode(userPwd);
       AssertUtil.isTrue(!userPwd.equals(userPwd1),"用户密码不正确");
    }

    private void checkLoginParams(String userName, String userPwd) {
        AssertUtil.isTrue(StringUtils.isBlank(userName),"用户姓名不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(userPwd),"密码不能为空");
    }

}
